package com.hang.aspect;

import com.hang.context.TenantContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1) // 在拦截器之后、事务切面之前执行
public class TransactionAspect {

    @Around("@annotation(org.springframework.transaction.annotation.Transactional)")
    public Object manageTransaction(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1. 获取当前租户编码
        String tenantCode = TenantContextHolder.getTenantCode();

        // 2. 若未设置数据源，回退到默认
        if (tenantCode == null) {
            tenantCode = "main";
            TenantContextHolder.setTenantCode(tenantCode);
        }

        // 3. 确保事务使用当前数据源
        return joinPoint.proceed();
    }
}
